package org.apache.ocean.solr.util;

import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntListIterator;

import java.util.Arrays;

/**
 * Uses binarysearch to keep int list sorted on add and remove
 * 
 */
public class SortedIntList {
	private IntArrayList list;

	public SortedIntList() {
		this.list = new IntArrayList();
	}

	public SortedIntList(int[] array) {
		this.list = new IntArrayList(array);
	}
  
	public int[] toIntArray() {
		return list.toIntArray();
	}
	
	public IntListIterator tailIterator(int i) {
		int index = Arrays.binarySearch(list.elements(), i);
		if (index < 0) {
			index = -index - 1;
		}
	  return list.listIterator(index);
	}

	public int size() {
		return list.size();
	}

	public IntIterator iterator() {
		return list.iterator();
	}

	public boolean contains(int i) {
		int index = Arrays.binarySearch(list.elements(), i);
		return index >= 0;
	}

	public int remove(int i) {
		int index = Arrays.binarySearch(list.elements(), i);
		return list.removeInt(index);
	}

	public int add(int i) {
		int index = Arrays.binarySearch(list.elements(), i);
		if (index < 0) {
			int insertIndex = -index - 1;
			list.add(insertIndex, i);
			return insertIndex;
		} else {
			return index;
		}
	}
}
